<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import { login, register } from '../api/auth'
import { ArrowLeft } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 登录表单数据
const loginForm = reactive({
    username: '',
    password: ''
})

// 注册表单数据
const registerForm = reactive({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
})

// 当前激活的标签页
const activeTab = ref('login')

// 根据 URL 参数设置初始标签页
onMounted(() => {
    if (route.query.tab === 'register') {
        activeTab.value = 'register'
    }
})

// 登录处理
const handleLogin = async () => {
    try {
        const res = await login(loginForm)
        if (res.code === 200 && res.data) {
            // 确保正确获取 token
            const token = res.data
            if (!token) {
                throw new Error('登录失败：未获取到token')
            }
            userStore.setToken(token)
            
            // 如果后端直接返回了用户信息，就直接使用
            if (res.data.userInfo) {
                userStore.setUserInfo(res.data.userInfo)
            } else {
                // 否则需要单独获取用户信息
                await userStore.fetchCurrentUser()
            }
            
            ElMessage.success('登录成功')
            
            // 获取重定向地址
            const redirect = localStorage.getItem('redirect') || '/'
            localStorage.removeItem('redirect')
            router.push(redirect)
        } else {
            throw new Error(res.message || '登录失败')
        }
    } catch (error) {
        console.error('Login error:', error)
        ElMessage.error(error.message || '登录失败')
    }
}

// 注册处理
const handleRegister = async () => {
    if (registerForm.password !== registerForm.confirmPassword) {
        ElMessage.error('两次输入的密码不一致')
        return
    }
    
    try {
        const { confirmPassword, ...registerData } = registerForm
        // 添加 nickname 字段，值与 username 相同
        const requestData = {
            ...registerData,
            nickname: registerData.username
        }
        
        const res = await register(requestData)
        if (res.code === 200) {
            ElMessage.success('注册成功，请登录')
            activeTab.value = 'login'
            loginForm.username = registerForm.username
        }
    } catch (error) {
        ElMessage.error('注册失败：' + (error.response?.data?.message || '未知错误'))
    }
}
</script>

<template>
    <div class="login-container">
        <div class="login-box">
            <div class="header">
                <img src="/images/logo.svg" alt="Logo" class="logo">
                <h2>欢迎来到技术社区</h2>
                <p class="subtitle">热爱技术，分享生活</p>
            </div>
            
            <el-tabs v-model="activeTab" class="login-tabs">
                <el-tab-pane label="登录" name="login">
                    <el-form :model="loginForm" class="login-form">
                        <el-form-item>
                            <el-input 
                                v-model="loginForm.username"
                                placeholder="用户名/邮箱"
                                prefix-icon="User"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-input 
                                v-model="loginForm.password"
                                type="password"
                                placeholder="密码"
                                prefix-icon="Lock"
                                show-password
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleLogin" class="submit-btn">
                                登录
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                
                <el-tab-pane label="注册" name="register">
                    <el-form :model="registerForm" class="login-form">
                        <el-form-item>
                            <el-input 
                                v-model="registerForm.username"
                                placeholder="用户名"
                                prefix-icon="User"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-input 
                                v-model="registerForm.email"
                                placeholder="邮箱"
                                prefix-icon="Message"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-input 
                                v-model="registerForm.password"
                                type="password"
                                placeholder="密码"
                                prefix-icon="Lock"
                                show-password
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-input 
                                v-model="registerForm.confirmPassword"
                                type="password"
                                placeholder="确认密码"
                                prefix-icon="Lock"
                                show-password
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleRegister" class="submit-btn">
                                注册
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
            
            <div class="other-login">
                <div class="divider">
                    <span>其他登录方式</span>
                </div>
                <div class="social-login">
                    <el-button class="social-btn">
                        <img src="/icons/wechat.svg" alt="微信" class="icon">
                        微信登录
                    </el-button>
                    <el-button class="social-btn">
                        <img src="/icons/qq.svg" alt="QQ" class="icon">
                        QQ登录
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
// 添加全局样式
:deep(body) {
  overflow: hidden;
}

.login-container {
  position: fixed;
  top: 60px; // header高度
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  overflow: hidden;
}

.login-box {
  width: 100%;
  max-width: 420px;
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
  
  .header {
    text-align: center;
    margin-bottom: 40px;
    
    .logo {
      width: 64px;
      height: 64px;
      margin-bottom: 24px;
    }
    
    h2 {
      font-size: 24px;
      color: #1a1a1a;
      margin-bottom: 8px;
    }
    
    .subtitle {
      font-size: 14px;
      color: #8c8c8c;
    }
  }
}

.login-tabs {
  :deep(.el-tabs__nav) {
    width: 100%;
    
    .el-tabs__item {
      width: 50%;
      text-align: center;
      font-size: 16px;
    }
  }
}

.login-form {
  margin-top: 24px;
  
  .submit-btn {
    width: 100%;
    padding: 12px;
    font-size: 16px;
  }
}

.other-login {
  margin-top: 40px;
  
  .divider {
    display: flex;
    align-items: center;
    color: #8c8c8c;
    font-size: 14px;
    margin-bottom: 24px;
    
    &::before,
    &::after {
      content: '';
      flex: 1;
      height: 1px;
      background: #e8e8e8;
    }
    
    span {
      padding: 0 16px;
    }
  }
  
  .social-login {
    display: flex;
    justify-content: center;
    gap: 16px;
    
    .social-btn {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .icon {
        width: 20px;
        height: 20px;
      }
    }
  }
}

@media screen and (max-width: 480px) {
  .login-box {
    padding: 20px;
  }
}
</style> 